package com.ponxu.mb.web.action.admin;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

import com.ponxu.log.Log;
import com.ponxu.log.LogFactory;
import com.ponxu.mb.Global;
import com.ponxu.mb.web.action.MiniBlogAction;
import com.ponxu.utils.Lang;
import com.ponxu.utils.TimeUtils;
import com.ponxu.web.core.WebContext;

/**
 * 文件管理
 * 
 * @author xwz
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class FileAction extends MiniBlogAction {
	private static final Log LOG = LogFactory.getLog();
	private static final String FTL_FILE = "/admin/file.ftl";

	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		return FTL_FILE;
	}

	public String manage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		WebContext context = new WebContext(request, response);

		final String UPLOAD_ROOT_DIR = Global.read("UPLOAD_ROOT_DIR");
		final String UPLOAD_ROOT_URL = Global.read("UPLOAD_ROOT_URL");
		final List<String> IMAGE_TYPES = Arrays.asList(Global.read(
				"IMAGE_TYPES").split(","));
		final List<String> SUB_DIR = Arrays.asList(new String[] { "image",
				"flash", "media", "file" });

		String rootPath = request.getSession().getServletContext()
				.getRealPath(UPLOAD_ROOT_DIR);
		String rootUrl = UPLOAD_ROOT_URL + UPLOAD_ROOT_DIR;
		LOG.debug("rootPath=%s", rootPath);

		String dirName = context.getParameter("dir");
		String path = context.getParameter("path");
		String order = context.getParameter("order");
		LOG.debug("dirName=%s, path=%s, order=%s", dirName, path, order);

		if (Lang.isEmpty(dirName) || !SUB_DIR.contains(dirName)) {
			context.write("Invalid Directory name.");
			return null;
		}

		rootPath += dirName + "/";
		rootUrl += dirName + "/";
		File saveDirFile = new File(rootPath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}

		String currentPath = rootPath + path;
		String currentUrl = rootUrl + path;

		String currentDirPath = path;
		String moveupDirPath = "";

		if (!"".equals(path)) {
			String str = currentDirPath.substring(0,
					currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0,
					str.lastIndexOf("/") + 1) : "";
		}

		// 不允许使用..移动到上一级目录
		if (path.indexOf("..") >= 0) {
			context.write("Access is not allowed.");
			return null;
		}

		// 最后一个字符不是/
		if (!"".equals(path) && !path.endsWith("/")) {
			context.write("Parameter is not valid.");
			return null;
		}

		// 目录不存在或不是目录
		File currentPathFile = new File(currentPath);
		if (!currentPathFile.isDirectory()) {
			context.write("Directory does not exist.");
			return null;
		}

		// 遍历目录取的文件信息
		List<Hashtable> fileList = new ArrayList<Hashtable>();
		File[] files = currentPathFile.listFiles();

		for (File file : files) {
			Hashtable<String, Object> hash = new Hashtable<String, Object>();
			String fileName = file.getName();
			if (file.isDirectory()) {
				hash.put("is_dir", true);
				hash.put("has_file", (file.listFiles() != null));
				hash.put("filesize", 0L);
				hash.put("is_photo", false);
				hash.put("filetype", "");
			} else if (file.isFile()) {
				String fileExt = getFileExt(fileName);
				hash.put("is_dir", false);
				hash.put("has_file", false);
				hash.put("filesize", file.length());
				hash.put("is_photo", IMAGE_TYPES.contains(fileExt));
				hash.put("filetype", fileExt);
			}
			hash.put("filename", fileName);
			hash.put("datetime", TimeUtils.format("yyyy-MM-dd HH:mm:ss",
					file.lastModified()));
			fileList.add(hash);
		}

		if ("size".equalsIgnoreCase(order)) {
			Collections.sort(fileList, new SizeComparator());
		} else if ("type".equalsIgnoreCase(order)) {
			Collections.sort(fileList, new TypeComparator());
		} else {
			Collections.sort(fileList, new NameComparator());
		}

		JSONObject result = new JSONObject();
		result.put("moveup_dir_path", moveupDirPath);
		result.put("current_dir_path", currentDirPath);
		result.put("current_url", currentUrl);
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);
		context.writeJSON(result);

		return null;
	}

	private String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
	}

	private class NameComparator implements Comparator {
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable) a;
			Hashtable hashB = (Hashtable) b;
			if (((Boolean) hashA.get("is_dir"))
					&& !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir"))
					&& ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String) hashA.get("filename"))
						.compareTo((String) hashB.get("filename"));
			}
		}
	}

	private class SizeComparator implements Comparator {
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable) a;
			Hashtable hashB = (Hashtable) b;
			if (((Boolean) hashA.get("is_dir"))
					&& !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir"))
					&& ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				if (((Long) hashA.get("filesize")) > ((Long) hashB
						.get("filesize"))) {
					return 1;
				} else if (((Long) hashA.get("filesize")) < ((Long) hashB
						.get("filesize"))) {
					return -1;
				} else {
					return 0;
				}
			}
		}
	}

	private class TypeComparator implements Comparator {
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable) a;
			Hashtable hashB = (Hashtable) b;
			if (((Boolean) hashA.get("is_dir"))
					&& !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir"))
					&& ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String) hashA.get("filetype"))
						.compareTo((String) hashB.get("filetype"));
			}
		}
	}
}